import {
	API_URL
} from '@/env.js'
import {
	router,
	RouterMount
} from "@/common/router.js"
import store from "@/store/index.js"
import md5 from 'js-md5';
const imageList = [];
const baseImageList = [];
const imgUrl = 'https://mystore-1304299581.cos.ap-guangzhou.myqcloud.com/static/image/'
/**
 * 常量：请求签名使用的公钥
 */
const AUTH_PUBLIC_KEY = 'bFBiDaqQyM9jSYmL7orND3YWUDm';
/**
 * 常量：请求签名的组合序列
 */
const AUTH_JOIN_ORDER = [0, 1, 2, 2, 1, 0, 2, 1];
export default {
	  // 签名
		make_sign(params) {
	    	let token = store.state.member.info.token;
		    let args = [md5(token), AUTH_PUBLIC_KEY, this.make_params_str(params)];
	    	let arr = [];
		    for (let i = 0; i < AUTH_JOIN_ORDER.length; i++) {
	    	    const j = AUTH_JOIN_ORDER[i];
	        	arr.push(args[j])
		    }
	    	return md5(arr.join('@')).toLocaleUpperCase();
		},
		// 对象转成字符串
		make_params_str(params) {
	    	let args = [];
		    let keys = Object.keys(params).sort(); // 排序处理
	    	for (let i in keys) {
	        	let key = keys[i];
				let strParams = JSON.stringify(params[key])
	        if (params.hasOwnProperty(key) && strParams !== '""' && strParams !== undefined  && strParams !== 'null') {
	            if (key != 'signature') {
	        	        args.push([key, strParams].join('='));
	    	        }
		        }
		    }
	    	return args.join('&');
		},
		// 时间戳
		timestamp() {
	    	return parseInt(new Date().getTime() / 1000);
		},
		// 随机字符串
		randstr(len = 32) {
	    	let chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
		    let maxPos = chars.length;
	    	let pwd = '';
		    for (let i = 0; i < len; i++) {
	    	    pwd += chars.charAt(Math.floor(Math.random() * maxPos));
		    }
	    	return pwd;
		},
	// 选择图片
	/**
	 * count        最多可以选择的图片张数
	 * sizeType     original 原图，compressed 压缩图
	 * sourceType   album 从相册选图，camera 使用相机
	 */
	chooseImage(count = 1) {
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count: count,
				sizeType: ['original', 'compressed'],
				sourceType: ['album'],
				success: res => {
					resolve(res.tempFilePaths);
				}
			})
		})
	},
	// 支付宝转码
	alypayBase64(imagePath) {
		let that = this;
		return new Promise((resolve, reject) => {
			my.getImageInfo({
				src: imagePath,
				success: async (res) => {
					this.imgWidth = res.width / 2.5;
					this.imgHeight = res.height / 2.5;
					let canvas = my.createCanvasContext("canvas");
					canvas.drawImage(imagePath, 0, 0, this.imgWidth, this
					.imgHeight); // 1. 绘制图片至canvas
					// // // console.log(canvas,'canvas');
					// 绘制完成后执行回调
					canvas.draw(false, async () => {
						// // // console.log('sssssssss');
						let base64 = await canvas.toDataURL({
							width: this.imgWidth,
							height: this.imgHeight,
							quality: 1,
						});
						this.base64 = base64;
						// // // console.log(base64,'base64');
						base64 = base64.replace('data:image/png;base64,', '');
						resolve(base64);
					});
				},
			});
		})
	},
	// 上传图片
	uploadImages(api, url) {
		let config_url = API_URL;
		uni.showLoading({
			title: '上传中'
		});
		return new Promise((resolve, reject) => {
			/**
			 *  url 服务器地址
			 *  fileType 支付宝小程序必填
			 *  filePath 要上传文件的路径
			 *  name 文件对应的key值，在服务端通过这个key值可以获取到二进制内容
			 *  success 回调函数
			 */
			uni.uploadFile({
				url: config_url + api,
				// #ifdef MP-ALIPAY 
				fileType: 'image', // 支付宝小程序必填
				// #endif
				filePath: url,
				name: 'file', // 根据后台进行修改
				success: res => {
					if (res.status === 200) {
						uni.hideLoading();
						uni.showToast({
							title: '上传成功',
							icon: 'none'
						});
						resolve(res.data);
					} else {
						uni.hideLoading();
						uni.showModal({
							title: '上传失败',
						});
					}
				},
				fail: e => {
					// // console.log(e, 'e');
				}
			})
		})
	},
	// 图片地址转成base64
	getFileSystemManager(url) {
		return new Promise((resolve, reject) => {
            uni.getFileSystemManager().readFile({
            	filePath: url,
            	encoding: "base64",
            	success: res => {
            		resolve(res);
            	},
            	fail: e => {
            		reject(e)
            	}
            })
			
		})
	},
    // 网络图片地址 转成 base64 
    getBase64(url) {
        return new Promise((resolve, reject) => {
            wx.downloadFile({
                url: url,
                success(res) {
                uni.getFileSystemManager().readFile({
                    	filePath: res.tempFilePath,
                    	encoding: "base64",
                    	success: res => {
                            // let imgUrl = 'data:image/png;base64,' + res.data;
                            let imgUrl = res.data;
                    		resolve(imgUrl);
                    	},
                    	fail: e => {
                    		reject(e)
                    	}
                    })
                }
            })
        	
        })
    },
	// 打电话
	callphone(phoneNumber = '') {
		let num = phoneNumber.toString();
		uni.makePhoneCall({
			phoneNumber: num,
			fail(err) {
				// // console.log('makePhoneCall有问题', err);
			}
		})
	},
	/**
	 * 弱提示框 - 支付宝小程序与微信小程序存在兼容性问题.详情看注解
	 * title 标题
	 * icon  图标  success loading  none
	 * duration 延迟 0为不关闭，毫秒数 
	 */
	toast(title, icon = "none", duration = 1500) {
		// #ifdef MP-WEIXIN
		uni.showToast({
			title: title,
			icon: icon,
			duration: duration
		})
		// #endif
		/**
		 * type 不支持loading  支持success fail none （exception 类型必须传文字)
		 */
		// #ifdef MP-ALIPAY
		my.showToast({
			content: title,
			type: icon,
			duration: duration
		})
		// #endif
	},
	// 复制至剪切板
	setClipboard(data) {
		uni.setClipboardData({
			data: data,
			success: function() {
				this.toast('已复制至剪切板')
			}
		})
	},
// 显示加载中
	showLoading(title="加载中",...data) {
		uni.showLoading({
			title:title
		})
	},
	// 处理时间
	time_data(val, type) {
	    if (!new Date(val)) return val;
	    let data = new Date(parseInt(val * 1000))
	    // // // console.log(val,'val')
	    let y = data.getFullYear();
	    let MM = data.getMonth() + 1;
	    MM = MM < 10 ? ('0' + MM) : MM
	    let d = data.getDate()
	    d = d < 10 ? ('0' + d) : d;
	    let h = data.getHours();
	    h = h < 10 ? ('0' + h) : h;
	    let m = data.getMinutes();
	    m = m < 10 ? ('0' + m) : m;
	    let s = data.getSeconds();
	    s = s < 10 ? ('0' + s) : s;
	    if (type == 'z_date') {
	        return y + '年' + MM + '月' + d + '日' + h + ':' + m 
	    }
	    if (type == 'd_date') {
	        return y + '年' + MM + '月' + d + '日  '
	    }
	    if (type == 'c_data') {
	        return y + '年' + MM + '月'
	    }
		if (type == 'b_date') {
			return y + '-' + MM + '-' + d
		}
		if (type == 'f_date') {
			return y + '.' + MM + '.' + d
		}
	    if (type == 'double') {
	        return y + '.' + MM + '.' + d + ' ' + h + ':' + m + ':' + s
	    }
        if (type == 'g_data') {
            return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s
        }
	    if (type == 'day') {
	        return MM + '-' + d + ' ' + h + ':' + m
	    }
	    return y + '.' + MM + '.' + d
	},
	// 隐藏加载中
	hideLoading() {
		uni.hideLoading();
	},
    // 获取dom（节点）信息
    // Vue.prototype.$getDom = function(name) {
    // 	return uni.createSelectorQuery().in(this).select(name).boundingClientRect()
    // }
    // 获取dom（节点）信息
    getDom(name) {
    	return uni.createSelectorQuery().in(this).select(name).boundingClientRect()
    },
    // 校验表单
    verification(v_data, form_rule) {
        var breaked = false;
        var error_message = null;
        for(var key in form_rule) {
            var rules = form_rule[key].rules;
            var type = form_rule[key].type;
            if(type == "form_data") {
                var l_length = rules.length;
                for(let k = 0;  k < l_length; k++ ) {
                  if(rules[k].rule.test(v_data[key]) != rules[k].v_res) {
    					breaked = true;
                        error_message = rules[k].message;
    					uni.showToast({
    						title: error_message,
    						icon: 'none',
    						duration: 2000
    					})
                        break ;
                  }
                }
            } else if(type == 'img') {
                if(v_data[key].length == 0) {
                        breaked = true;
                        error_message = form_rule[key].message;
    					uni.showToast({
    						title: error_message,
    						icon: 'none',
    						duration: 2000
    					})
                        break ;
                }
            }
            if(breaked) {break;}
        }
        if(breaked) {
            return {status: false,  message: error_message};
        } else {
            return {status: true, message: null}
        }
    }
	

}
